import { createRouter, createWebHistory } from 'vue-router';
import type { Router } from 'vue-router';
import { useUserStore } from '@/store/modules/user';
import { useEnumStore } from '@/store/modules/enum';
import routes from './routes';

const router: Router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: routes,
});

router.beforeEach(async (to, _from, next) => {
  const userStore = useUserStore();
  const enumStore = useEnumStore();

  if (userStore.isLoggedIn && !userStore.userInfo) {
    try {
      await userStore.getUserInfo();
    } catch (error) {
      console.error('获取用户信息失败', error);
      await userStore.logout();
      next({
        path: '/login',
        replace: true,
      });
      return;
    }
  }

  // 已登录时在路由切换阶段确保枚举已加载（loadAllEnums 内部有去重控制）
  if (userStore.isLoggedIn) {
    try {
      await enumStore.loadAllEnums(true);
    } catch (error) {
      console.error('加载枚举数据失败', error);
    }
  }

  if (!userStore.isLoggedIn && to.path !== '/login') {
    next({
      path: '/login',
      replace: true,
    });
    return;
  }

  if (userStore.isLoggedIn && to.path === '/login') {
    next({
      path: '/product',
      replace: true,
    });
    return;
  }

  next();
});

export default router;
